package com.whfc.emp.manager.impl;

import com.whfc.emp.dao.AppBroadcastRecordEmpMapper;
import com.whfc.emp.entity.AppBroadcastRecordEmp;
import com.whfc.emp.enums.AppBroadcastSendState;
import com.whfc.emp.manager.AppBroadcastManager;
import com.whfc.hdc.dto.AppDeviceDTO;
import com.whfc.hdc.service.AppDeviceService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClasssName AppBroadcastManagerImpl
 * @Description 广播服务
 * @Author hw
 * @Date 2021/1/4 16:01
 * @Version 1.0
 */
@Service
public class AppBroadcastManagerImpl implements AppBroadcastManager {

    @Autowired
    private AppBroadcastRecordEmpMapper appBroadcastRecordEmpMapper;

    @DubboReference(interfaceClass = AppDeviceService.class, version = "1.0.0")
    private AppDeviceService commonDeviceService;

    @Override
    public void updateBroadcastState(Integer id, String code, Integer state) {
        if (id != null) {
            appBroadcastRecordEmpMapper.updateState(id, state);
        } else {
            AppDeviceDTO deviceDTO = commonDeviceService.getDeviceByCode(code);
            List<AppBroadcastRecordEmp> recordEmpList = appBroadcastRecordEmpMapper.selectUndoneByDeviceId(deviceDTO.getId());
            for (int i = 0; i < recordEmpList.size(); i++) {
                AppBroadcastRecordEmp recordEmp = recordEmpList.get(i);
                if (i == 0) {
                    //同一个设备，修改最后一条的状态，其它默认为失效
                    recordEmp.setState(state);
                } else {
                    recordEmp.setState(AppBroadcastSendState.EXPIRED.getValue());
                }
                appBroadcastRecordEmpMapper.updateState(recordEmp.getId(), recordEmp.getState());
            }
        }
    }
}
